/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Text, Table, TableRow, TableBody, Cell, useTheme, Button, InputLine, Input, SuffixInput, LineColumn, TextArea, BlobInputList, CCell,
} from "customize-easy-ui-component";
import {
    CCellUnit, InspectRecordLayout, InternalItemProps, useInputControlSure,
} from "../../common/base";
import {useMeasureInpFilter} from "../../common/hooks";
import {tableSetInp} from "../../../common/tool";
import {TailMenRowIspCheck} from "../../contain/rarelyVary";
import queryString from "query-string";
import {EditStorageContext} from "../../StorageContext";
import {useUppyUploadM} from "../../hook/useUppyUploadM";
import {DirectLink, Link as RouterLink} from "../../../routing/Link";
import {useFoldForList, useFoldGenerate, useSplitSubCapacity} from "../../hook/useMainRepUrlOr";

//【特殊性】类似可重复的分项报告的做法， 可是没有使用独立分项报告的框架！原始记录跟随主报告的且只能显示出第一个块内容。缺点：setInp嵌套对象层次太深了！getInpFilter提取整个table;
//【权衡】考虑，若该子报告真的没有用到表格数组的录入编辑情形的就可以用这种模式。后者还是考虑走通常的分项报告框架模式吧。
export interface ReproducibleProps extends InternalItemProps {
    table: string;
    iAname?: string[];
}
/** 可重复分项的【简易模式】：
 @param dxtix : 同一个重复分项的序号；
 【非常特殊的】 实际名字 是在<DimensionInsp table={'尺寸表'} 注入的； @ 唯一性检查！
 export const itemA联络附页=[ ];
* */
export const DimensionInsp=
    React.forwardRef(({ children, show ,alone=true,redId,nestMd,refWidth,rep,table,label,iAname}:ReproducibleProps,  ref
    ) => {
        const qs= queryString.parse(window.location.search);
        const dxtix =Number(qs?.dxtix) || 0;
        const {modified,setModified,} =React.useContext(EditStorageContext) as any;
        const itemA = React.useMemo(() => {
            return [ table,  ...(iAname||[]) ];
        }, [ table,iAname]);
        const [getInpFilter]=useMeasureInpFilter(null,itemA,);
        const {inp, setInp,onSure} = useInputControlSure({ ref,redId,nestMd });
        const dxtSize= inp?.[table]?.length || 0;
        const row=undefined===inp?.[table]?.[dxtix]? dxtSize : dxtix;
        const onFinish = React.useCallback(async(forRow:number, upfile: any, del:boolean) => {
            if(inp){
                tableSetInp(table, row, inp, onSure, '_FILE_', (del? undefined : upfile), false);
                !modified && setModified(true);
            }
        }, [row, inp, modified,table,onSure,setModified]);
        //只能上传唯一一个图片的做法：
        const [uploadDom]=useUppyUploadM({repId:rep?.id, table:table,
                     row: row,  inp, setInp, onFinish, liveDays:1});

        return (
            <InspectRecordLayout inp={inp} setInp={setInp} getInpFilter={getInpFilter} show={show}
                                 alone={alone} label={`${label} ${dxtix + 1} 的管理`}>
                <Text variant="h5">
                  {label}，序号 {dxtix + 1}：
                </Text>
                <LineColumn>
                    <InputLine label='部件名称：'>
                        <Input value={inp?.[table]?.[row]?.部件 || ''}
                               onChange={e => tableSetInp(table, row, inp, setInp, '部件', e.currentTarget.value || undefined)}/>
                    </InputLine>
                    <InputLine label='仪器名称：'>
                        <Input value={inp?.[table]?.[row]?.仪器 || ''}
                               onChange={e => tableSetInp(table, row, inp, setInp, '仪器', e.currentTarget.value || undefined)}/>
                    </InputLine>
                    <InputLine label='仪器编号：'>
                        <Input value={inp?.[table]?.[row]?.仪器编 || ''}
                               onChange={e => tableSetInp(table, row, inp, setInp, '仪器编', e.currentTarget.value || undefined)}/>
                    </InputLine>
                    <InputLine label='仪器精度:'>
                        <SuffixInput value={inp?.[table]?.[row]?.精度 || ''}
                                     onSave={txt => tableSetInp(table, row, inp, setInp, '精度', txt || undefined)}
                        >mm</SuffixInput>
                    </InputLine>
                </LineColumn>
                {children}
                <hr/>
                {label} 检查部位示意图：
                {uploadDom}
                检验情况及意见：
                <BlobInputList  value={inp?.[table]?.[row]?.尺寸结果 ||''} rows={4} onListChange={v => tableSetInp(table, row, inp, setInp, '尺寸结果', v || undefined)}
                                datalist={['符合要求。']}
                />
                备注：
                <TextArea  value={inp?.[table]?.[row]?.尺寸备注 ||''} rows={4}
                           onChange={e => tableSetInp(table, row, inp, setInp, '尺寸备注', e.currentTarget.value || undefined)}/>

                { !(inp?.[table]?.[row]?._FILE_?.url) ?
                    <Text variant="h5">
                        没有上传的文件，想要：
                        <Button intent="danger"
                                onPress={async () => {
                                    // inp?.部图表?.splice(delNo! - 1, delSize);
                                    tableSetInp(table, row, inp, onSure, '_FILE_', undefined ,true);
                                    // setInp({...inp, 部图表: inp?.部图表,});      //等效setInp({...inp})
                                }}
                        >执行管理对象的删除</Button>，然后自行离开本界面，返回。
                    </Text>
                    :
                    <Text variant="h6">
                     注：必须删除上传的文件，然后才能执行管理对象的删除。
                    </Text>
                }
            </InspectRecordLayout>
        );
    });

export interface ReproducibleVwProps{
    orc: any;
    rep: any;
    children?: React.ReactNode;
    table: string;
    //折叠标签的名称：
    title: string;
    //可修改tag ID的关联；
    hash?: string;
}
/**编辑器组件可自定义的： 【局限性】只能支持一个图片的。
 * */
export const DimensionInspVw= ({ orc, rep, children,table,title,hash}: ReproducibleVwProps
) => {
    const theme = useTheme();
    const sizeDg = orc?.[table]?.length || 0;
    const lsBlockMax = useSplitSubCapacity(sizeDg, 8);        //以8张图为一个折叠区组合的。 实际图序号计算 =折叠区序号 * 8 +偏移量。
    const {sumArea, areaContent, btnBindUses} = useFoldForList(orc?.[table], lsBlockMax, false);
    //若独占一整页：下面第二个div <div css={{"@media print": {height: '100vh', overflowY: 'hidden',}}}>
    const callback = (dlPage: any, arak: number, pid: number) => {
        const aIdx = arak * lsBlockMax + pid;      //在总体列表中的顺序号。
        return <div key={aIdx} css={{"@media not print": {marginTop: '1rem', marginBottom: '1rem'},}}>
            <div>
                <DirectLink
                    href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/DimensionInsp#DimensionInsp`}>
                    <div css={{"@media print": {paddingBottom: '3.5rem', pageBreakInside: 'avoid'}}}>
                        <Text id='LargeSlabBeam' variant="h2" css={{
                            textAlign: 'center', marginTop: '1rem',
                        }}>尺寸检查报告 {aIdx ? aIdx : ''}</Text>
                        <div css={{display: 'flex', justifyContent: 'space-between'}}>
                            <Text>序号：{aIdx + 1}</Text>
                            <Text>报告编号：{rep.isp.no}</Text>
                        </div>
                    </div>
                </DirectLink>
                <Table fixed={["9%", "25%", "9%", "22%", "9%", "%"]}
                       css={{borderCollapse: 'collapse', "@media print": {marginTop: '-3.5rem'}}} tight miniw={800}>
                    <TableBody>
                        <DirectLink
                            href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/DimensionInsp?dxtix=` + aIdx + `#DimensionInsp`}>
                            <TableRow>
                                <CCell>锅炉型号</CCell><CCell colSpan={2}>{orc.型号 ?? '／'}</CCell>
                                <CCell>部件名称</CCell><CCell colSpan={2}>{orc?.[table]?.[aIdx]?.部件 ?? '／'}</CCell>
                            </TableRow>
                            <TableRow>
                                <CCell>仪器名称</CCell><CCell>{orc?.[table]?.[aIdx]?.仪器 ?? '／'}</CCell>
                                <CCell>仪器编号</CCell><CCell>{orc?.[table]?.[aIdx]?.仪器编 ?? '／'}</CCell>
                                <CCell>仪器精度</CCell><CCellUnit unit='mm'>{orc?.[table]?.[aIdx]?.精度 ?? '／'}</CCellUnit>
                            </TableRow>
                            <TableRow>
                                <Cell colSpan={6} css={{
                                    "@media print": {
                                        height: '-webkit-fill-available',
                                        pageBreakInside: 'avoid'
                                    }, padding: 0,
                                }}>
                                    检查部位示意图：
                                    <div css={{
                                        display: 'flex', justifyContent: 'space-around', alignItems: 'center',
                                        "@media print": {
                                            marginTop: '1px', marginRight: '1px', marginBottom: '1px',
                                            minHeight: undefined
                                        },
                                    }}>
                                        {!orc?.[table]?.[aIdx]?._FILE_?.url && '/'}
                                        {orc?.[table]?.[aIdx]?._FILE_?.url &&
                                            <img
                                                src={process.env.REACT_APP_OSS_ENDP + orc?.[table]?.[aIdx]?._FILE_?.url}
                                                alt={orc?.[table]?.[aIdx]?._FILE_?.url}
                                                css={{
                                                    maxHeight: '14cm',
                                                    maxWidth: '-webkit-fill-available',
                                                    [theme.mediaQueries.lg]: {maxHeight: '18cm', maxWidth: undefined},
                                                    "@media print": {maxHeight: '86vh', maxWidth: '100%'},
                                                }}
                                            />
                                        }
                                    </div>
                                    <div css={{textAlign: 'right'}}>（单位：mm）</div>
                                </Cell>
                            </TableRow>
                            <TableRow>
                                <Cell split={true} colSpan={6}><div css={{minHeight: '3rem', whiteSpace: 'pre-wrap'}}>
                                    检验情况及意见：<br/>
                                    {orc?.[table]?.[aIdx]?.尺寸结果 || '／'}
                                </div></Cell>
                            </TableRow>
                            <TableRow>
                                <Cell split={true} colSpan={6}><div css={{minHeight: '3rem', whiteSpace: 'pre-wrap'}}>
                                    备注：<br/>
                                    {orc?.[table]?.[aIdx]?.尺寸备注 || '／'}
                                </div></Cell>
                            </TableRow>
                        </DirectLink>
                    </TableBody>
                </Table>
                <TailMenRowIspCheck orc={orc} rep={rep}
                                    href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/ProjectList#ProjectList`}>
                </TailMenRowIspCheck>
            </div>
        </div>
    }

    const [renderAll] = useFoldGenerate({sumArea, btnBindUses, areaContent, callback, mark: title + '折叠'});
    const dxtNext = (orc?.[table]?.length || 0);
    return <>
        {sizeDg <= 0 &&
            <RouterLink
                href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/DimensionInsp#DimensionInsp`}>
                <Text id='DrawingsExplan' variant="h4" css={{
                    textAlign: 'center', marginTop: '1rem', "@media print": {display: 'none',},
                }}>{title}-的录入</Text>
            </RouterLink>
        }
        <div id={hash ?? "DimensionInsp"}/>
        {renderAll}
        <RouterLink
            href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/DimensionInsp?dxtix=${dxtNext}#DimensionInsp`}>
            <Text variant="h3" css={{
                textAlign: 'center', "@media print": {display: 'none',},
            }}>新增加 {title}</Text>
        </RouterLink>
    </>;
};
